package services.common;

import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import models.common.bean.Shareholder;
import models.common.bean.ShareholderSignBean;
import models.common.bean.TicketBao;
import models.common.bean.TicketQuota;
import models.common.bean.TransferCredits;
import models.common.bean.commercialPaperInfo;
import models.common.entity.t_amount_detail;
import models.common.entity.t_amount_detail.CrawlType;
import models.common.entity.t_commercial_paper_info;
import models.common.entity.t_commercial_paper_info.TicketStatus;
import models.common.entity.t_commercial_paper_lines;
import models.common.entity.t_commercial_paper_lines.PaperStatus;
import models.common.entity.t_commercial_paper_record;
import models.common.entity.t_company_info;
import models.common.entity.t_creditor_right_debt;
import models.common.entity.t_creditor_right_debt.CreditorRightDebtStatus;
import models.common.entity.t_deal_user;
import models.common.entity.t_digital_commercial_paper;
import models.common.entity.t_digital_commercial_paper.DigitalStatus;
import models.common.entity.t_endorse;
import models.common.entity.t_send_code;
import models.common.entity.t_shareholder;
import models.common.entity.t_user;
import models.common.entity.t_user_fund;

import org.apache.commons.lang.StringUtils;

import play.db.jpa.JPAPlugin;
import services.base.BaseService;

import common.constants.ConfConst;
import common.enums.HoldControllingType;
import common.enums.NoticeScene;
import common.enums.ServiceType;
import common.utils.DateToIntUtil;
import common.utils.DateUtil;
import common.utils.Factory;
import common.utils.ImgUtil;
import common.utils.LoggerUtil;
import common.utils.OrderNoUtil;
import common.utils.PageBean;
import common.utils.ResultInfo;
import common.utils.StrUtil;
import common.utils.number.Arith;

import daos.common.CommerciaPaperLinesDao;
import daos.common.PactDao;

/**
 * 商票额度表
 *@author xiaojun
 *@version 2017-4-14 下午4:26:50
 */
public class CommerciaPaperLinesService extends BaseService<t_commercial_paper_lines> {
	
	private CommerciaPaperLinesDao commerciaPaperLinesDao  ;
	protected CommerciaPaperLinesService(){
	
		commerciaPaperLinesDao=Factory.getDao(CommerciaPaperLinesDao.class);
		super.basedao = commerciaPaperLinesDao;
	}
	protected static ShareholderSignService shareholderSignService = Factory.getService(ShareholderSignService.class);
	protected static SendCodeRecordsService sendCodeRecordsService = Factory.getService(SendCodeRecordsService.class);
	protected static UserInfoService userInfoservice = Factory.getService(UserInfoService.class);
	protected static UserService userservice = Factory.getService(UserService.class);
	protected static NoticeService noticeservice = Factory.getService(NoticeService.class);
	protected static CompanyInfoService companyInfoService= Factory.getService(CompanyInfoService.class);
	protected static CommerciaPaperiInfoService commerciaPaperiInfoService = Factory.getService(CommerciaPaperiInfoService.class);
	protected static ShareholderService shareholderService=Factory.getService(ShareholderService.class);
	protected static PactService pactService=Factory.getService(PactService.class);
	
	protected static DealUserService dealUserService = Factory.getService(DealUserService.class);
	protected static CreditorRightDebtService creditorRightDebtService = Factory.getService(CreditorRightDebtService.class);

	protected static CommerciaPaperRecordService commerciaPaperRecordService=Factory.getService(CommerciaPaperRecordService.class);
	protected static UserFundService userFundService = Factory.getService(UserFundService.class);
	protected static DigitalCommercialPaperService digitalCommercialPaperService=Factory.getService(DigitalCommercialPaperService.class);
	protected static EndorseService	endorseService	=Factory.getService(EndorseService.class);
	protected static AmountDetailService amountDetailService=Factory.getService(AmountDetailService.class);

	/**
	 * 后台-风控页面-质押商票的列表
	 * @param showType 筛选类型    0全部 1审核中 2 已质押3 已完成 4 未通过 5 已失效 6  已到期 7  已逾期 8 待签字 9已签字 
	 * @param currPage 
	 * @param pageSize
	 * @param exports 1:导出  default：不导出
	 * @param orderType  排序类型
	 * @param orderValue 
	 * @param creditorName  债权人全称
	 * @param numNo 编号
	 * @param debtPersonName  债务人全称
	 * @param type 0 风控 1 财务
	 * @return
	 * @author xiaojun
	 * @createDate  2017年4月15日
	 */
	public PageBean<commercialPaperInfo> pageOfBidRisk(int showType, int currPage, int pageSize, int exports,int orderType,int orderValue,String creditorName,String numNo,String debtPersonName,int type) {
		
		return commerciaPaperLinesDao.pageOfBidRisk(showType, currPage, pageSize, exports, orderType, orderValue, creditorName, numNo, debtPersonName,type);
	}
	
	/**
	 * 后台-风控页面-质押商票的列表计算商票金额
	 * @param showType  筛选类型    0全部 1审核中 2 已质押3 已完成 4 未通过 5 已失效 6  已到期 7  已逾期 8 待签字 9已签字 
	 * @param creditorName  债权人全称
	 * @param numNo 编号
	 * @param debtPersonName  债务人全称
	 * @return
	 *  @author xiaojun
	 * @createDate  2017年4月15日
	 */
	  public double findTotalTicketAmount(int showType, String creditorName, String numNo, String debtPersonName,int type){
		
		List<Integer> statusList = new ArrayList<Integer>();
		switch (showType) {
			case 0://所有
				if(type==1){
					statusList.add(PaperStatus.EXPIRE.code);
					statusList.add(PaperStatus.OVERDUE.code);
				}
				break;
			case 1:{//审核中
				statusList.add(PaperStatus.PREAUDITING.code);
				break;
			}
			case 2:{//已质押
				statusList.add(PaperStatus.PLEDGE.code);
				break;
			}
			case 3:{//已完成
				statusList.add(PaperStatus.ACCOMPLISH.code);
				break;
			}
			case 4:{//未通过
				statusList.add(PaperStatus.NOT_PASS.code);
				break;
			}
			case 5:{//已失效
				statusList.add(PaperStatus.LOSE_EFFICACY.code);
				break;
			}
			case 6:{//已到期
				statusList.add(PaperStatus.EXPIRE.code);
				break;
			}
			case 7:{//已逾期
				statusList.add(PaperStatus.OVERDUE.code);
				break;
			}
			case 8:{//待签字
				statusList.add(PaperStatus.TO_SIGNATURE.code);
				break;
			}
			case 9:{//已签字
				statusList.add(PaperStatus.SIGNATURE.code);
				break;
			}
			case 10:{//待关联
				statusList.add(PaperStatus.TO_RELEVANCE.code);
				break;
			}
			case 11:{//已关联
				statusList.add(PaperStatus.RELEVANCE.code);
				break;
			}
			case 12:{//已取消
				statusList.add(PaperStatus.CANCEL.code);
				break;
			}
			case 13:{//赎回中
				statusList.add(PaperStatus.REDEMPTION_REQUESTS.code);
				break;
			}
			case 14:{//已赎回
				statusList.add(PaperStatus.REDEMPTION.code);
				break;
			}
			default:
				break;
		}

		return commerciaPaperLinesDao.findTotalTicketAmount(statusList, creditorName, numNo, debtPersonName,type);
	}
 	
	  /**
	   * 质押审核数据校验
	   *
	   * @param cplid 额度id
	   * @param suggest 审核意见
	   * @param type 商票类型
	   * @param finacing_total_limit 额度
	   * @param bond_percent 保证金比例
	   * @param allow_finacing 是否自融
	   * @param self_limit 自融额度
	   * @param status 状态
	   * @return
	   * @author xiaojun
	   *@version 2017-11-13
	   */
	  public ResultInfo validateAuditTicket(long cplid,String suggest,int type,double finacing_total_limit,double bond_percent,int allow_finacing,double self_limit,int status){
		  ResultInfo result = new ResultInfo();
		  if (cplid < 0) {
				result.code = -1;
				result.msg="质押商票的信息有误!";
				return result;
			}
			if (StringUtils.isBlank(suggest) || suggest.length() < 20
					|| suggest.length() > 300) {
				result.code = -1;
				result.msg="风控建议长度位于20~300位之间!";
				return result;
			}
			if (type < 0 || type > 3) {
				result.code = -1;
				result.msg="请选择商票类型 数字商票/ECDS商票";
				return result;
			}
			// 验证金额
			if (finacing_total_limit < 0) {
				result.code = -1;
				result.msg="请输入正确的融通额度";
				return result;
			}
			// 验证保证金
			if (bond_percent < 0 || bond_percent > 100) {
				result.code = -1;
				result.msg="请输入0~100的数字";
				return result;
			}
			// 验证是否可自融
			if (allow_finacing != 0 && allow_finacing != 1) {
				result.code = -1;
				result.msg="输入错误";
				return result;
			}
			// 验证自融金额
			if (self_limit < 0) {
				result.code = -1;
				result.msg="请输入正确的金额";
				return result;
			}
			// 验证状态
			if (status != 1 && status != 7 && status != 9) {
				result.code = -1;
				result.msg="状态错误";
				return result;
			}
			result.code = 1;
			result.msg="校验通过";
			return result;
	  }
	/**
	 * 后台-风控页面-质押商票审核（签字/已质押）
	 * @param cplid 商票额度表id
	 * @param finacing_total_limit 融通额度
	 * @param bond_percent  保证金比例
	 * @param allow_finacing 是否可以自融  0不可以 1 可以
	 * @param self_limit 自融额度
	 * @param suggest  审核建议
	 * @param status  状态
	 * @param is_shareholder_sign  是否签字
	 * @param type 商票类型 0 ECDS商票 1 数字商票 2 关联ECDS商票
	 * @return
	 * @author xiaojun
	 * @createDate  2017年4月15日
	 */
	  public ResultInfo preAuditTicketThrough(long cplid,double finacing_total_limit,double bond_percent,int allow_finacing,double self_limit,
				String suggest,int status,int is_shareholder_sign,int type){
		  ResultInfo result = new ResultInfo();
		  t_commercial_paper_lines cpl=super.findByID(cplid);
		  if(cpl == null){
				result.code = -1;
				result.msg = "查询质押商票失败";
				
				return result;
			}
		  t_commercial_paper_info cpi=commerciaPaperiInfoService.findByID(cpl.commer_paper_id);
		  if(!t_commercial_paper_lines.PaperStatus.PREAUDITING.equals(cpl.getStatus())){
				result.code = -1;
				result.msg = "非法审核状态";				
				return result; 
			}
		if(self_limit > cpi.paper_money){
			result.code = -1;
			result.msg = "自融额度不能大于商票金额";				
			return result; 
		}
		if(finacing_total_limit > cpi.paper_money){
			result.code = -1;
			result.msg = "融通额度不能大于商票金额";				
			return result; 
		}  
		List<Integer>nowstatus = new ArrayList<Integer>();
		nowstatus.add(t_commercial_paper_lines.PaperStatus.PREAUDITING.code);
//		原始商票id就是 数字商票转开就沿用上一张商票的原始商票id 如果是关联商票 就是关联那张商票的原始商票id, 其他都是本商票id
		long oiginal_id=cpl.oiginal_id;
		double finacing_available_limit=finacing_total_limit;
		if(cpl.is_turned==1){//如果是数字商票转开  融通总额度 、融通可用额度、 保证金比例、原始商票id都是数字商票转开的时候设定过的数据
			finacing_total_limit=cpl.finacing_total_limit;
			finacing_available_limit=cpl.finacing_available_limit;
			bond_percent=cpl.bond_percent;
			type=1;
		}
		cpl.contract_id="";
		t_user tu = userservice.findByID(cpl.user_id);
		/** 发送邮件、站内信、短信通知用户 */
		Map<String, Object> content = new HashMap<String, Object>();
		content.put("user_name", tu.company_full_name);
		content.put("bill_code", cpl.bill_code);//质押票号
		if(status==1 ){
//			更新商票 持票人为平台 0 
			
			if(cpl.financing_type==2){
				t_endorse endorse=endorseService.findByID(cpl.financing_type_id);
				t_digital_commercial_paper dcp= digitalCommercialPaperService.findByID(endorse.digital_id);
				dcp.certificate_code = cpi.certificate_code;
				cpi.paper_pic_under=ImgUtil.screenshot(dcp,4,cpi,null);
			}else if(cpl.financing_type==1){
				t_digital_commercial_paper dcp= digitalCommercialPaperService.findByID(cpl.financing_type_id);
				dcp.certificate_code = cpi.certificate_code;
				cpi.paper_pic_under=ImgUtil.screenshot(dcp,4,cpi,null);
			}
			
			cpi.receive_id=0;
			boolean update = commerciaPaperiInfoService.updateTicket(cpi);
			if(!update){
				result.code = -1;
				result.msg = "商票数据异常，请稍后尝试";
			 }

//			添加商票跟踪表信息
			t_commercial_paper_record commercialPaperRecord = new t_commercial_paper_record();
			commercialPaperRecord.commer_paper_id = cpi.id;
			commercialPaperRecord.type = t_commercial_paper_record.RecordType.PLEDGE.code;
			commercialPaperRecord.open_ticket_id = cpl.user_id;
			commercialPaperRecord.receive_id = 0; // 为平台
			commercialPaperRecord.operator_id = cpl.user_id;
			commercialPaperRecord.paper_datetime = new Date();
			boolean save= commerciaPaperRecordService.saveCommerciaPaperRecord(commercialPaperRecord);
			if(!save){
				result.code=-1;
				result.msg="新增商票跟踪表数据异常";
			}
			
			/** 审核通过  发送通知 */
			noticeservice.sendSysNotice(cpl.user_id, NoticeScene.PLEDGE_OK, content);
		}else  if(status==9){
			/** 待关联  发送通知 质押用户*/
				content.put("drawee", cpi.drawee);
			/** 待关联  发送通知 质押关联企业*/
			t_company_info companyInfo = companyInfoService.findIDByName("full_name=?",cpi.drawee.trim());
			Map<String, Object> contents = new HashMap<String, Object>();
			contents.put("user_name", companyInfo.full_name);
			contents.put("bill_code", cpl.bill_code);
			contents.put("company", tu.company_full_name);
		}
		if(status==9){
			type=2;
			cpl.is_turned = 1;
		}
		if(type == 3){
			finacing_total_limit = cpi.paper_money;
			finacing_available_limit = cpi.paper_money;
		}
//		最大用户授信额度
		if(cpl.is_turned == 0){
			t_user_fund user_fund = userFundService.queryUserFundByUserId(cpl.user_id);
			if(user_fund == null){
				result.code = -1;
				result.msg = "用户账户异常！";
				return result;
			}
			double maxLimit = Arith.sub(user_fund.max_amount, user_fund.use_amount);
			if(finacing_total_limit > maxLimit){
				result.code = -1;
				result.msg = "融通额度不能大于可用信用额度";
				return result;
			}
			user_fund.use_amount +=finacing_total_limit;
			if(!userFundService.saveAmount(user_fund)){
				result.code = -1;
				result.msg = "更新可用信用额度失败";
				return result;
			}
		}	
//		
		int i = commerciaPaperLinesDao.preAuditTicketStatus(cplid,finacing_total_limit,bond_percent, allow_finacing, self_limit,
				suggest,status,is_shareholder_sign, nowstatus,type,oiginal_id,finacing_available_limit,cpl.contract_id);
		if(i != 1){
			result.code = -1;
			result.msg = "审核失败";
			return result;
		}
		
		result.code = 1;
		result.obj = cpl;
		return result;
	  }
	  
	  /**
	   * 后台-风控页面-质押商票审核（未通过）
	   * @param cplid
	   * @return
	   */
	  public ResultInfo preAuditTicketNotThrough(long cplid,String suggest){
		  ResultInfo result = new ResultInfo();
		  t_commercial_paper_lines cpl=super.findByID(cplid);
		  if(cpl == null){
				result.code = -1;
				result.msg = "查询质押商票失败";
				
				return result;
			}
		  if(!t_commercial_paper_lines.PaperStatus.PREAUDITING.equals(cpl.getStatus())){
				result.code = -1;
				result.msg = "非法审核状态";				
				return result;
			}
		  
		  List<Integer>nowstatus = new ArrayList<Integer>();
			nowstatus.add(t_commercial_paper_lines.PaperStatus.PREAUDITING.code);			
			int i = commerciaPaperLinesDao.preAuditTicketNotStatus(cplid,nowstatus,PaperStatus.NOT_PASS.code,suggest);
			if(i != 1){
				result.code = -1;
				result.msg = "审核失败";
				return result;
			}
			
			result.code = 1;
			result.obj = cpl;
			  return result;
	  }
	  /**
		 * 后台-风控页面-质押商票签字审核 签字表查询
		 * @param commer_paper_lines_id
		 * @return
		 * @author xiaojun
		 * @createDate 2017年4月18日
		 */
	  public List<Shareholder> findShareholder(long commer_paper_lines_id){
		 return commerciaPaperLinesDao.findShareholder(commer_paper_lines_id);
	  }
	  
	  
	  /**
	   * 后台-风控页面-质押商票签字审核
	   * @param cplid
	   * @return
	   * @author xiaojun
		 * @createDate 2017年4月18日
	   */
	  public ResultInfo signatureAuditTicketNotThrough(long cplid,int status,String suggest){
		  ResultInfo result = new ResultInfo();
		  t_commercial_paper_lines cpl=super.findByID(cplid);
		  if(cpl == null){
				result.code = -1;
				result.msg = "查询质押商票失败";
				
				return result;
			}
		  if(!t_commercial_paper_lines.PaperStatus.SIGNATURE.equals(cpl.getStatus()) && !t_commercial_paper_lines.PaperStatus.TO_SIGNATURE.equals(cpl.getStatus())){
				result.code = -1;
				result.msg = "非法审核状态";				
				return result;
			}
		  
		  List<Integer>nowstatus = new ArrayList<Integer>();
		  nowstatus.add(t_commercial_paper_lines.PaperStatus.SIGNATURE.code);
		  nowstatus.add(t_commercial_paper_lines.PaperStatus.TO_SIGNATURE.code);
			int i = commerciaPaperLinesDao.preAuditTicketNotStatus(cplid,nowstatus,status,suggest);
			if(i != 1){
				result.code = -1;
				result.msg = "审核失败";
				
				return result;
			}
			
			result.code = 1;
			result.obj = cpl;
			t_user tu = userservice.findByID(cpl.user_id);
			/** 发送邮件、站内信、短信通知用户 */
			Map<String, Object> content = new HashMap<String, Object>();
			content.put("user_name", tu.name);
			content.put("bill_code", cpl.bill_code);//质押票号
				

			  return result;
	  }
	  
	  /**
	   * 挂牌融通-申请融通
	   * @param creditor_right_debt 债权信息
	   * @return 
	   * @author xiaojun
	   * @createDate 2017年5月8日
	   */
	  public boolean addCommercialPaperLines(t_creditor_right_debt creditor_right_debt){
		  t_commercial_paper_lines t=new t_commercial_paper_lines();
		  t.user_id=creditor_right_debt.company_id;
		  t.creditor_right_id=creditor_right_debt.id;
		//  t.commer_paper_id=creditor_right_debt.commer_paper_id;
		  t.type=t_commercial_paper_lines.PaperType.ECDS_TICKET.code;
		  t.apply_time=new Date();
		  /*t_commercial_paper_info cpi=commerciaPaperiInfoService.findByID(creditor_right_debt.commer_paper_id);
		  t.bill_code="";
		  if(cpi==null){ 
			  return false;
		  }
		  t.bill_code=cpi.bill_code;
		  t.paper_expire_time=cpi.paper_expire_time;
		  t.oiginal_id=cpi.id;*/
		  t.comer_paper_status = t_commercial_paper_lines.PaperStatus.SIGN_FOR.code;
		  return commerciaPaperLinesDao.save(t);
	  }
	  /**
		 * 查询 商票宝，票信通，债权通的挂牌信息
		 * @param userId 企业用户id
		 * @param type 商票类型  债权通：0 1 商票宝：2
		 * @return page TicketBao bean
		 * @author liaijun
		 * @createDate 2017年5月9日
		 */
	  public PageBean<TicketBao> queryPageBean(long userId,int type){
		  return commerciaPaperLinesDao.queryPageBean(userId, type);		  
	  }
 
	  /**
		 * 查询 商票宝，票信通，债权通的挂牌信息
		 * @param id 额度id
		 * @return page TicketBao bean
		 * @author liaijun
		 * @createDate 2017年5月9日
		 */
      public TicketBao queryTicket(long id){
		 
	     return commerciaPaperLinesDao.queryTicket(id);		  
	  }
      
      
      /**
		 * 查询 商票宝，票信通，债权通的挂牌 挂牌缴纳保证金
		 * @param id 额度id
		 * @return page TicketBao bean
		 * @author liaijun
		 * @createDate 2017年5月9日
		 */
     public TicketBao findTicket(long id){
	    return commerciaPaperLinesDao.querTicket(id);		  
	 }
      
   	/**
   	 * 前台	-账户中心-交易管理-商票列表-审核列表
   	 * @param showType  筛选类型    0全部 1审核中 2 已质押3 已完成 4 未通过 5 已失效 6  已到期 7  已逾期 8 待签字 9已签字10待关联 11已关联 12取消关联 
   	 * @param type 0 所有 1 ECDS商票 2 数字商票 3 收到的ECDS商票
   	 * @param currPage
   	 * @param pageSize
   	 * @param exports  1:导出  default：不导出
   	 * @param	user_id 用户id
   	 * @param	checkin_time 申请时间 条件（开始）
   	 * @param	to_checkin_time 申请时间 条件（结束）
   	 * @author xiaojun
   	 * @createDate 2017年5月11日
   	 *
   	 */
   	public PageBean<commercialPaperInfo> pageOfReviewList(int showType,int type, int currPage, int pageSize, int exports,long user_id,String checkin_time,String to_checkin_time,String drawee) {
		return commerciaPaperLinesDao.pageOfReviewList(showType,type, currPage, pageSize, exports, user_id, checkin_time, to_checkin_time,drawee);
   	
   	}
 	/**
 	 * 前台	-账户中心-交易管理-商票列表-金额计算
 	 * @param showType  筛选类型    0全部 1审核中 2 已质押3 已完成 4 未通过 5 已失效 6  已到期 7  已逾期 8 待签字 9已签字10待关联 11已关联 12取消关联 
 	 * @param type  0 所有 1 ECDS商票 、收到的ECDS商票 2 数字商票 
 	 * @param currPage
 	 * @param pageSize
 	 * @param exports  1:导出  default：不导出
 	 * @param	user_id 用户id
 	 * @param	checkin_time 申请时间 条件（开始）
 	 * @param	to_checkin_time 申请时间 条件（结束）
 	 * @author xiaojun
 	 * @createDate 2017年5月11日
 	 *
 	 */
 	public TicketQuota pageOfTicketQuota(int showType,int type,long user_id,String checkin_time,String to_checkin_time,String drawee) {
 		return commerciaPaperLinesDao.pageOfTicketQuota(showType, type, user_id, checkin_time, to_checkin_time,drawee);
 	}
 	/**
 	 * 关联确认列表金额计算
 	 *
 	 * @param type  0 待关联  1 已关联
 	 * @param checkin_time  开始时间
 	 * @param to_checkin_time  结束时间
 	 * @param drawee  付款公司全称
 	 * @return
 	 * @author xiaojun
 	 *@version 2017-8-16
 	 */
 	public double findECDSTicketAmount(int showType,int type,String checkin_time,String to_checkin_time,String drawee){
 		return  commerciaPaperLinesDao.findECDSTicketAmount(showType, type, checkin_time, to_checkin_time, drawee);
 	}
 	
 	/**
 	 * 更新商票额度表数据
 	 *
 	 * @param t 商票额度表实体
 	 * @return
 	 * @author xiaojun
 	 *@version 2017-5-3 下午7:20:42
 	 */
 	public boolean saveCommercialPaper(t_commercial_paper_lines t){
 		return commerciaPaperLinesDao.save(t);
 	}
	/**
	 * 更新数字商票表状态
	 *
	 * @param t 数字商票实体
	 * @return
	 * @author xiaojun
	 *@version 2017-5-3 下午7:20:42
	 */
	
	  public boolean updateStatus(int status, int olStatus,long id){
			  return commerciaPaperLinesDao.updateStatus(status, olStatus, id);		 
	  }
	/**
	 * 前台-账户中心-交易管理-商票列表-数字商票ecds关联额度列表-关联商票
	 *
	 * @param loadId 选择的额度信息id
	 * @param newId 待关联的额度id
	 * @param paper_money 关联金额
	 * @author xiaojun
	 *@version 2017-5-17
	 */
 	public ResultInfo associatedQuota(long loadId,long newId,double paper_money){
 		ResultInfo result = new ResultInfo();
 		if(paper_money <= 0){
 			result.code = -1;
 			result.msg = "关联金额异常！";
 			return result;
 		}
		t_commercial_paper_lines newCpl=findByID(newId);
		t_commercial_paper_lines loadCpl=findByID(loadId);
		if(newCpl==null||newCpl.comer_paper_status!=PaperStatus.TO_RELEVANCE.code){
			result.code = -1;
 			result.msg = "待关联额度表的状态异常！";
 			return result;
		}
		
		if(loadCpl==null||loadCpl.comer_paper_status!=PaperStatus.PLEDGE.code && loadCpl.comer_paper_status!=PaperStatus.RELEVANCE.code){
			result.code = -1;
 			result.msg = "选择关联额度表的状态异常！";
 			return result;
		}
		loadCpl.finacing_available_limit-=paper_money; 
		loadCpl.finacing_used_limit+=paper_money;
		loadCpl.listed_amount += paper_money;
		newCpl.finacing_available_limit+=paper_money;
		newCpl.finacing_total_limit=paper_money;
		newCpl.bond_percent=loadCpl.bond_percent;
		if(loadCpl.oiginal_id==0){
			newCpl.oiginal_id=loadCpl.commer_paper_id;
		}else{
			newCpl.oiginal_id=loadCpl.oiginal_id;
		}
		newCpl.is_turned=1;
		newCpl.financing_type = 3;
		newCpl.financing_type_id = loadCpl.id;		
		boolean save = saveCommercialPaper(loadCpl);
		if(!save){
			LoggerUtil.error(true, "选择关联的额度表更新额度信息失败");
			result.code = -1;
 			result.msg = "选择关联的额度表更新额度信息失败！";
 			return result;
		}
		 save = saveCommercialPaper(newCpl);
		if(!save){
			LoggerUtil.error(true, "待关联额度表数据更新信息失败");
			result.code = -1;
 			result.msg = "待关联的额度表更新额度信息失败！";
 			return result;
		}
		save = updateStatus(PaperStatus.RELEVANCE.code, PaperStatus.TO_RELEVANCE.code, newCpl.id);
		if(!save){
			result.code = -1;
 			result.msg = "状态非法！";
 			return result;
		}
//		更新商票 持票人为平台 0 
		t_commercial_paper_info cpi=commerciaPaperiInfoService.findByID(newCpl.commer_paper_id);
		cpi.receive_id=0;
		cpi=commerciaPaperiInfoService.addTicket(cpi);
		if(cpi==null){
			LoggerUtil.error(true, "待关联商票数据更新信息失败");
			result.code = -1;
 			result.msg = "待关联商票数据更新信息失败！";
 			return result;
		 }
//		添加商票跟踪表信息
		t_commercial_paper_record commercialPaperRecord=new t_commercial_paper_record();
		commercialPaperRecord.commer_paper_id=cpi.id;
		commercialPaperRecord.type=t_commercial_paper_record.RecordType.PLEDGE.code;
		commercialPaperRecord.open_ticket_id=newCpl.user_id;
		commercialPaperRecord.receive_id=0; // 为平台
		commercialPaperRecord.operator_id=newCpl.user_id;
		commercialPaperRecord.paper_datetime=new Date();
		 save= commerciaPaperRecordService.saveCommerciaPaperRecord(commercialPaperRecord);
		if(!save){
			LoggerUtil.error(true, "新增商票跟踪表数据异常");
			result.code = -1;
 			result.msg = "新增商票跟踪表数据异常！";
 			return result;
		}
		t_creditor_right_debt crd=creditorRightDebtService.findByID(loadCpl.creditor_right_id);
//		添加额度明细表信息
		t_amount_detail amountDetail=new t_amount_detail(loadCpl.id,crd.creditor_name,new Date(),paper_money,loadCpl.finacing_available_limit,CrawlType.ASSOCIATEDTICKET.code,crd.contract_name_code,loadCpl.finacing_total_limit);
		boolean saveDetail= amountDetailService.saveAmountDetail(amountDetail);
		if(!saveDetail){
			LoggerUtil.error(true,"新增额度明细异常");
			result.code = -1;
 			result.msg = "新增额度明细异常！";
 			return result;
		}
	
		result.code = 1;
		result.msg = "关联成功，更新状态为："+newCpl.getStatus().value;
		return result;
 	}
	/**
	 * 前台-账户中心-交易管理-商票列表-数字商票ecds关联额度列表-取消关联商票
	 *
	 * @param id 额度表id
	 * @author xiaojun
	 *@version 2017-5-17
	 */
	public  ResultInfo  deauthentication(long id){
		ResultInfo result =new ResultInfo();
		t_commercial_paper_lines cpl=findByID(id);
		if(cpl==null||cpl.comer_paper_status!=PaperStatus.TO_RELEVANCE.code){
			result.code=-1;
			result.msg="状态非法";
			return result;
		}
//		更新额度表状态为 已取消
		cpl.comer_paper_status = PaperStatus.CANCEL.code;
		boolean save = updateStatus(PaperStatus.CANCEL.code, PaperStatus.TO_RELEVANCE.code, id);
		if(!save){
			result.code=-1;
			result.msg="更新额度表状态数据异常";
			LoggerUtil.error(true, "更新额度表状态数据异常");
			return result;
		}
		t_creditor_right_debt creditorRightDebt=creditorRightDebtService.findByID(cpl.creditor_right_id);
		//修改商票债权状态 为 已登记
		creditorRightDebt.status=t_creditor_right_debt.CreditorRightDebtStatus.REGISTER.code;
		boolean savecrd=creditorRightDebtService.updateStatus(creditorRightDebt);
		if(!savecrd){
			LoggerUtil.error(true, "修改债权债权状态失败");
			result.code=-1;
			result.msg="修改债权债权状态失败";
			return result;
		}
		result.code=1;
		result.msg="操作成功！已更新状态为："+cpl.getStatus().value;
		return result;
	}
 	
 	
	/**
	 * 前台-账户中心-交易管理- 商票列表-ECDS商票-关联ECDS商票查询
	 * @param user_id  登录用户的id
	 * @return
	 * @author xiaojun
	 * @createDate 2017年5月18日
	 */
	public List<TransferCredits> findECDS(long user_id,double finacing_available_limit){
		return commerciaPaperLinesDao.findECDS(user_id,finacing_available_limit);
	}
	/**
 	 * 更新商票额度表数据(sql语句)
 	 *
 	 * @param id 商票额度表实体
 	 * @param update_criteria 更新那些信息
 	 * @return
 	 * @author liaijun
 	 *@version 2017-5-3 下午7:20:42
 	 */
 	public int upDateCommercialPaper(long id,double amount){
 		
 		String update_criteria ="tcpl. - :amount,tcpl.freezing_limit + :amount";
		Map<String, Object> args = new HashMap<String, Object>();
		args.put("id", id);
		args.put("amount",amount);
 		return commerciaPaperLinesDao.upDateCommercialPaper(update_criteria,args); 
 	}
 	protected PactDao pactDao = Factory.getDao(PactDao.class);
 	


	/**
	 * 定时任务-标记商票质押额度到期
	 *
	 * @return
	 * @author xiaojun
	 *@version 2017-5-24
	 */
	public ResultInfo systemVerfallpfand(){
		ResultInfo result =new ResultInfo();
//		将到期的待签收背书流转强制撤回
		result=endorseService.autocancelEndorse();
		if(result.code<0){
			return result;
		}
//		将到期的待签收数字商票强制撤回
		result=digitalCommercialPaperService.autocancelDigital();
		if(result.code<0){
			return result;
		}
//		将到期的审核中质押票强制撤回
		result=autocancelPreauditing();
		if(result.code<0){
			return result;
		}
		return commerciaPaperLinesDao.autoVerfallpfand();
	}
 	/**
 	 * 将到期的审核中质押票强制撤回
 	 *
 	 * @return
 	 * @author xiaojun
 	 *@version 2017-6-29
 	 */
	public ResultInfo autocancelPreauditing(){
 		ResultInfo result = new ResultInfo();
 		List<t_commercial_paper_lines> commercialList = commerciaPaperLinesDao.autocancelPreauditing();
 		if(commercialList != null && commercialList.size()>0){
 			for(int i = 0;i<commercialList.size();i++){
 				t_commercial_paper_lines cpl = commercialList.get(i);
 				result = cancelPreauditing(cpl.id);
 				if(result.code<0){
 					return result;
 				}
 			}
 		}
		return result;
 		
 	}
	/**
	 * 将到期的审核中质押票强制撤回
	 *
	 * @param id  额度表id
	 * @return
	 * @author xiaojun
	 *@version 2017-6-29
	 */
	public ResultInfo cancelPreauditing(long id){
		ResultInfo result = new ResultInfo();
		t_commercial_paper_lines cpl=findByID(id);
		if(cpl==null || (cpl.comer_paper_status != PaperStatus.PREAUDITING.code && cpl.comer_paper_status != PaperStatus.SIGN_FOR.code)){
			result.code=-1;
			result.msg="状态非法";
			return result;
		}
//		更新额度表状态为 已撤回
		cpl.comer_paper_status=PaperStatus.ACCOMPLISH.code;
		boolean save=saveCommercialPaper(cpl);
		if(!save){
			result.code=-1;
			result.msg="更新额度表状态数据异常";
			LoggerUtil.error(true, "更新额度表状态数据异常");
			return result;
		}
		t_creditor_right_debt creditorRightDebt=creditorRightDebtService.findByID(cpl.creditor_right_id);
		//修改商票状态 
		if(cpl.financing_type==0){
			creditorRightDebt.status=t_creditor_right_debt.CreditorRightDebtStatus.REGISTER.code;
			boolean savecrd=creditorRightDebtService.updateStatus(creditorRightDebt);
			if(!savecrd){
				LoggerUtil.error(true, "修改债权债权状态失败");
				result.code=-1;
				result.msg="修改债权债权状态失败";
				return result;
			}
		}else if(cpl.financing_type==1){
			t_digital_commercial_paper dcp=digitalCommercialPaperService.findByID(cpl.financing_type_id);
			dcp.digital_com_status=DigitalStatus.CONFIRM.code;
			dcp.is_endorse=0;//操作类型 0未操作
			boolean savecrd=digitalCommercialPaperService.saveDigitalPapreB(dcp);
			if(!savecrd){
				LoggerUtil.error(true,"更新数字商票状态异常");
				result.code=-1;
				result.msg="更新数字商票状态异常";
				return result;
			}
		}else if(cpl.financing_type==2){
			t_endorse endorse=endorseService.findByID(cpl.financing_type_id);
			endorse.receive_endorse_status=DigitalStatus.CONFIRM.code;
			boolean savecrd=endorseService.saveEndorse(endorse);
			if(!savecrd){
				LoggerUtil.error(true,"更新背书状态异常");
				result.code=-1;
				result.msg="更新背书状态异常";
				return result;
			}
		}
		

		result.code=1;
		result.msg="操作成功！已更新状态为："+cpl.getStatus().value;
		return result;
	}
	
	/**
	 * 定时任务-系统标记商票质押额度逾期
	 *
	 * @return
	 * @author xiaojun
	 *@version 2017-5-24
	 */
	public ResultInfo systemTicketAmounMarkOverdue(){
		return commerciaPaperLinesDao.autoTicketAmounMarkOverdue();
	}
	/**
	 * 定时任务-商票质押额度到期自动兑现
	 *
	 * @return
	 * @author xiaojun
	 *@version 2017-5-24
	 */
	public ResultInfo systemTicketAmounCash(){
		ResultInfo result = new ResultInfo();
//		查出到期的质押商票
		List<t_commercial_paper_lines> list=commerciaPaperLinesDao.findAutoCash( t_commercial_paper_lines.PaperStatus.EXPIRE.code);
		if(list==null||list.size()==0){
			 result.code=1;
			 result.msg="没有商票质押到期";
			return result;
		}
		/* 关闭自动事务 */
		   JPAPlugin.closeTx(false);
		for(t_commercial_paper_lines cpl:list){
			/* 开启自动投标事务 */
			JPAPlugin.startTx(false);
			result.msg="没有转开商票质押到期";
			if(cpl.is_turned==1){
				result.msg="原商票未结清";
				t_commercial_paper_info oldcpi = commerciaPaperiInfoService.findByID(cpl.oiginal_id);
				if(oldcpi!=null&&oldcpi.paper_status == t_commercial_paper_info.TicketStatus.ALL_SQUARED.code){
					
					t_commercial_paper_info cpi = commerciaPaperiInfoService.findByID(cpl.commer_paper_id);
//					更新商票的状态为：已结清
					cpi.paper_status = TicketStatus.ALL_SQUARED.code;
					cpi.cash_all_amount = cpl.finacing_total_limit;
					cpi.cash_amount = cpl.finacing_total_limit;
					cpi.collection_status = 1;
					cpi=commerciaPaperiInfoService.addTicket(cpi);
					if(cpi==null){
						result.code=-1;
						result.msg="商票状态更新失败";
					}
					t_company_info company_info=companyInfoService.findByColumn(" full_name=?", cpi.drawee);
					if(company_info==null){
						result.code=-1;
						result.msg="查询付款人信息失败";
					}
					 if(cpl.financing_type==1){
						t_digital_commercial_paper dcp= digitalCommercialPaperService.findByID(cpl.financing_type_id);
						
//				   		   更新数字商票状态
						dcp.digital_com_status=t_digital_commercial_paper.DigitalStatus.LOSE_EFFICACY.code;
						boolean save= digitalCommercialPaperService.saveDigitalPapreB(dcp);
						if(!save){
							result.code=-1;
							result.msg="数字商票状态更新失败";
						}
					}else if(cpl.financing_type==2){//背书后申请融通额度
						t_endorse endorse=endorseService.findByID(cpl.financing_type_id);
						t_digital_commercial_paper dcp= digitalCommercialPaperService.findByID(endorse.digital_id);
						
//				   		   更新数字商票状态
						dcp.digital_com_status=DigitalStatus.LOSE_EFFICACY.code;
						boolean save= digitalCommercialPaperService.saveDigitalPapreB(dcp);
						if(!save){
							result.code=-1;
							result.msg="数字商票状态更新失败";
						}
//				   		   更新背书流转状态
						 endorse.receive_endorse_status=DigitalStatus.LOSE_EFFICACY.code;	
							save= endorseService.saveEndorse(endorse);
							if(!save){
								result.code=-1;
								result.msg="背书状态更新失败";
							}
					}
//					订单号
					String serviceOrderNo = OrderNoUtil.getNormalOrderNo(ServiceType.TICKET_CASH,OrderNoUtil.COMMERICAL_ORDER_NORMAL);
					result=doAutoCash(cpl.id, serviceOrderNo);
					if (result.code < 0) {
						 result.code=-1;
						 result.msg="自动兑换商票金额失败";
						return result;
					}
				}
			}
			/* 关闭自动事务 */
			   JPAPlugin.closeTx(false);
		}
		/* 开启自动投标事务 */
		JPAPlugin.startTx(false);
		result.code=1;
	
		return result;
	}
	
	/**
	 * 兑现修改商票状态
	 *
	 * @param cplid  额度表id
	 * @return
	 * @author xiaojun
	 *@version 2017-5-26
	 */
	public ResultInfo updateCashStatus(long cplid){
		ResultInfo result = new ResultInfo();
		t_commercial_paper_lines cpl = findByID(cplid);
		t_commercial_paper_info cpi=commerciaPaperiInfoService.findByID(cpl.commer_paper_id);
		if(cpl.comer_paper_status!=PaperStatus.EXPIRE.code && cpl.comer_paper_status!=PaperStatus.OVERDUE.code){
			result.code = -1;
			result.msg = "该商票质押信息状态非法";
			return result;
		}
		//额度表失效
		cpl.comer_paper_status=t_commercial_paper_lines.PaperStatus.LOSE_EFFICACY.code;
		if(!saveCommercialPaper(cpl)){
			result.code=-1;
			result.msg="额度表数据异常";
			return result;
		}
//		商票状态为：已结清
		cpi.paper_status=t_commercial_paper_info.TicketStatus.ALL_SQUARED.code;
		cpi.cash_all_amount=cpl.finacing_total_limit;
		cpi.cash_amount=cpl.finacing_total_limit;
		cpi.collection_status=1;
		cpi=commerciaPaperiInfoService.addTicket(cpi);
		if(cpi==null){
			result.code=-1;
			result.msg="商票数据异常";
			return result;
		}
		result.code=1;
		return result;
	}

	/**
	 * 商票兑现（平台管理人员执行）
	 * 
	 * @param cplid 额度ID
	 * @param serviceOrderNo 业务订单号
	 * @return
	 *
	 * @author xiaojun
	 * @createDate 2017年5月23日
	 */
	public ResultInfo doCash(long cplid,  String serviceOrderNo) {
		ResultInfo result = new ResultInfo();
		
		t_commercial_paper_lines cpl = findByID(cplid);
		if (cpl == null) {
			result.code = -1;
			result.msg = "该商票质押信息不存在";
			return result;
		}
		
//		查询商票信息
		t_commercial_paper_info cpi=commerciaPaperiInfoService.findByID(cpl.commer_paper_id);
		    //商票兑现金额
		double receiveAmt = cpl.finacing_total_limit; 
		
		boolean isSignSuccess = true;  //用户签名是否通过
		result = userFundService.userFundSignCheck(cpl.user_id);
		if (result.code < 1) {
			isSignSuccess = true;
		}
//		增加用户可用余额	
		boolean addFund = userFundService.userFundAdd(cpl.user_id, receiveAmt);
		if (!addFund) {
				result.code = -1;
				result.msg = "增加持票人可用余额失败";
				
				return result;
			}
//		冻结用户已用额度金额	
		if( cpl.finacing_used_limit>0){
			 addFund = userFundService.userFundFreeze(cpl.user_id, cpl.finacing_used_limit);
		}
		
		if (!addFund) {
				result.code = -1;
				result.msg = "冻结用户已用额度金额失败";
				
				return result;
			}
			//刷新持票人资金信息
			t_user_fund investUserFund = userFundService.queryUserFundByUserId(cpl.user_id);
			if (investUserFund == null) {
				result.code = -1;
				result.msg = "获取持票人资金信息失败";
				
				return result;
			}
			
			//如果投资用户账户资金没有遭到非法改动，那么就更新其篡改标志，否则不更新
			if(isSignSuccess){
				userFundService.userFundSignUpdate(cpl.user_id);
			}

			//添加质押商户收款记录
			Map<String, String> summaryParam = new HashMap<String, String>();
			summaryParam.put("bill_code", cpi.bill_code);
			/*boolean addDeal = dealUserService.addDealUserInfo(
					serviceOrderNo,
					cpl.user_id, 
					cpi.paper_money, 
					investUserFund.balance,   
					investUserFund.freeze, 
					t_deal_user.OperationType.DUE_PAYMENT,
					summaryParam);
			if (!addDeal) {
				result.code = -1;
				result.msg = "添加持票人收款记录失败";
				
				return result;
			}*/
			
 			//通知质押人
 		Map<String, Object> sceneParame = new HashMap<String, Object>();
 		sceneParame.put("user_name", investUserFund.name);
 		sceneParame.put("bill_code",cpi.bill_code);
 		sceneParame.put("paper_money", receiveAmt);
 		sceneParame.put("freeze", cpl.finacing_used_limit);
 		noticeservice.sendSysNotice(cpl.user_id, NoticeScene.DUE_PAYMENT, sceneParame);
		
		result.code = 1;
		result.msg = "商票兑现成功";
		return result;
	}
	
	/**
	 * 商票兑现（自动执行）
	 * 
	 * @param cplid 额度ID
	 * @param serviceOrderNo 业务订单号
	 * @return
	 *
	 * @author xiaojun
	 * @createDate 2017年5月23日
	 */
	public ResultInfo doAutoCash(long cplid,  String serviceOrderNo) {
		ResultInfo result = new ResultInfo();
		
		t_commercial_paper_lines cpl = findByID(cplid);
		if (cpl == null) {
			result.code = -1;
			result.msg = "该商票质押信息不存在";
			return result;
		}
		if(cpl.comer_paper_status != t_commercial_paper_lines.PaperStatus.EXPIRE.code && cpl.comer_paper_status != t_commercial_paper_lines.PaperStatus.OVERDUE.code){
			result.code = -1;
			result.msg = "该商票质押信息状态非法";
			return result;
		}
//		更新额度表状态
		cpl.comer_paper_status=t_commercial_paper_lines.PaperStatus.LOSE_EFFICACY.code;
		if(!saveCommercialPaper(cpl)){
			result.code = -1;
			result.msg = "该商票质押信息状态非法";
			return result;
		}
//		查询商票信息
		t_commercial_paper_info cpi=commerciaPaperiInfoService.findByID(cpl.commer_paper_id);
		    //商票兑现金额
		double receiveAmt = cpl.finacing_total_limit; 
		
		boolean isSignSuccess = true;  //用户签名是否通过
		result = userFundService.userFundSignCheck(cpl.user_id);
		if (result.code < 1) {
			isSignSuccess = false;
		}
//		增加用户可用余额	
		boolean addFund = userFundService.userFundAdd(cpl.user_id, receiveAmt);
		if (!addFund) {
				result.code = -1;
				result.msg = "增加持票人可用余额失败";
				return result;
			}
		if(cpl.finacing_used_limit>0){
//			冻结用户已用额度金额	
			 addFund = userFundService.userFundFreeze(cpl.user_id, cpl.finacing_used_limit);
			if (!addFund) {
					result.code = -1;
					result.msg = "冻结用户已用额度金额失败";
					return result;
				}
		}

			//刷新持票人资金信息
			t_user_fund investUserFund = userFundService.queryUserFundByUserId(cpl.user_id);
			if (investUserFund == null) {
				result.code = -1;
				result.msg = "获取持票人资金信息失败";
				
				return result;
			}
			
			//如果投资用户账户资金没有遭到非法改动，那么就更新其篡改标志，否则不更新
			if(isSignSuccess){
				userFundService.userFundSignUpdate(cpl.user_id);
			}

			//添加质押商户收款记录
			Map<String, String> summaryParam = new HashMap<String, String>();
			summaryParam.put("bill_code", cpi.bill_code);
			/*boolean addDeal = dealUserService.addDealUserInfo(
					serviceOrderNo,
					cpl.user_id, 
					cpi.paper_money, 
					investUserFund.balance,   
					investUserFund.freeze, 
					t_deal_user.OperationType.DUE_PAYMENT,
					summaryParam);
			if (!addDeal) {
				result.code = -1;
				result.msg = "添加持票人收款记录失败";
				
				return result;
			}*/
			
 			//通知质押人
 		Map<String, Object> sceneParame = new HashMap<String, Object>();
 		sceneParame.put("user_name", investUserFund.name);
 		sceneParame.put("bill_code",cpi.bill_code);
 		sceneParame.put("paper_money", receiveAmt);
 		sceneParame.put("freeze", cpl.finacing_used_limit);
 		noticeservice.sendSysNotice(cpl.user_id, NoticeScene.DUE_PAYMENT, sceneParame);
		
//		付款人
		t_company_info company_info=companyInfoService.findByColumn(" full_name=?", cpi.drawee);
		
		 isSignSuccess = true;  //用户签名是否通过
		result = userFundService.userFundSignCheck(company_info.user_id);
		if (result.code < 1) {
			isSignSuccess = false;
		}
		
//		减去付款人冻结金额
		 addFund = userFundService.userFundMinusFreezeAmt(company_info.user_id, receiveAmt);
		if (!addFund) {
				result.code = -1;
				result.msg = "减去付款人冻结金额失败";
				return result;
			}
		
		//刷新付款人资金信息
		t_user_fund refreshUserFund = userFundService.queryUserFundByUserId(company_info.user_id);
		if (refreshUserFund == null) {
			result.code = -1;
			result.msg = "获取付款人资金信息失败";
			
			return result;
		}
		
		//如果付款人账户资金没有遭到非法改动，那么就更新其篡改标志，否则不更新
		if(isSignSuccess){
			userFundService.userFundSignUpdate(company_info.user_id);
		}
		
		//添加付款人付款记录
		 summaryParam = new HashMap<String, String>();
		summaryParam.put("bill_code", cpi.bill_code);
		 /*addDeal = dealUserService.addDealUserInfo(
				serviceOrderNo,
				company_info.user_id, 
				cpl.finacing_total_limit, 
				refreshUserFund.balance,   
				refreshUserFund.freeze, 
				t_deal_user.OperationType.EXPIRE_REIMBURSEMENT,
				summaryParam);
		if (!addDeal) {
			result.code = -1;
			result.msg = "添加付款人付款记录失败";
			
			return result;
		}*/
		
			//通知付款人
		 sceneParame = new HashMap<String, Object>();
		sceneParame.put("user_name", refreshUserFund.name);
		sceneParame.put("bill_code",cpi.bill_code);
		sceneParame.put("amount", receiveAmt);
		noticeservice.sendSysNotice(company_info.user_id, NoticeScene.EXPIRE_REIMBURSEMENT, sceneParame);
		
		result.code = 1;
		result.msg = "商票兑现成功";
		return result;
	}
	/**
	 * 质押商票赎回申请审核
	 *
	 * @param cplid
	 * @param status
	 * @param suggest
	 * @return
	 * @author xiaojun
	 *@version 2017-6-2
	 */
	public ResultInfo redemptionAudit(long cplid,int status ,String suggest){
		ResultInfo result = new ResultInfo();
		t_commercial_paper_lines cpl=findByID(cplid);
//		审核通过 需把债权、商票 状态还原 
		if(status==t_commercial_paper_lines.PaperStatus.REDEMPTION.code){
			if(cpl.financing_type==0||cpl.financing_type==3){//financing_type:融通类型 0 ECDS商票融通 1数字商票融通，2 背书商票融通,3、关联额度

//				更新商票状态 为已登记
				t_commercial_paper_info cpi=commerciaPaperiInfoService.findByID(cpl.commer_paper_id);
				cpi.paper_status=t_commercial_paper_info.TicketStatus.REGISTER.code;
				cpi=commerciaPaperiInfoService.addTicket(cpi);
				if(cpi==null){
					result.code=-1;
					result.msg="商票数据异常，请稍后尝试";
					return result;
				 }
				t_creditor_right_debt crd=creditorRightDebtService.findByID(cpl.creditor_right_id);
				crd.status=CreditorRightDebtStatus.REGISTER.code;
				 boolean save=creditorRightDebtService.addCreditorRightDebt(crd);
				 if(!save){
						result.code=-1;
						result.msg="商票债权数据异常，请稍后尝试";
						return result;
				 }
			 }else if(cpl.financing_type==1){//修改数字商票的状态为 已确认
				 t_digital_commercial_paper digital_commercial_paper= digitalCommercialPaperService.findByID(cpl.financing_type_id);
				 digital_commercial_paper.digital_com_status=DigitalStatus.CONFIRM.code;
				 digital_commercial_paper.is_endorse=0;//操作类型 0未操作
				 boolean save=digitalCommercialPaperService.saveDigitalPapreB(digital_commercial_paper);
				 if(!save){
						result.code=-1;
						result.msg="数字商票数据异常，请稍后尝试";
						return result;
				 }
			 }else if(cpl.financing_type==2){
				 t_endorse endorse= endorseService.findByID(cpl.financing_type_id);
				 endorse.receive_endorse_status=DigitalStatus.CONFIRM.code;
				 boolean  save=endorseService.saveEndorse(endorse);
				 if(!save){
						result.code=-1;
						result.msg="背书数据异常，请稍后尝试";
						return result;
				 }
			 }
//			更新商票 持票人为质押人
			t_commercial_paper_info cpi=commerciaPaperiInfoService.findByID(cpl.commer_paper_id);
			cpl.remove_pledge_time=new Date();
			if(cpl.financing_type==2){
				t_endorse endorse=endorseService.findByID(cpl.financing_type_id);
				t_digital_commercial_paper dcp= digitalCommercialPaperService.findByID(endorse.digital_id);
				cpi.paper_pic_under=ImgUtil.screenshot(dcp,4,cpi,null);
			}else if(cpl.financing_type==1){
				t_digital_commercial_paper dcp= digitalCommercialPaperService.findByID(cpl.financing_type_id);
				cpi.paper_pic_under=ImgUtil.screenshot(dcp,4,cpi,null);
			}
			cpi.receive_id=cpl.user_id;
			cpi=commerciaPaperiInfoService.addTicket(cpi);
			if(cpi==null){
				result.code=-1;
				result.msg="商票数据异常，请稍后尝试";
				return result;
			}
//			添加商票跟踪表信息
			t_commercial_paper_record commercialPaperRecord=new t_commercial_paper_record();
			commercialPaperRecord.commer_paper_id=cpi.id;
			commercialPaperRecord.type=t_commercial_paper_record.RecordType.REMOVE_PLEDGE.code;
			commercialPaperRecord.receive_id=cpl.user_id;
			commercialPaperRecord.operator_id=cpl.user_id;
			commercialPaperRecord.paper_datetime=new Date();
			boolean save= commerciaPaperRecordService.saveCommerciaPaperRecord(commercialPaperRecord);
			if(!save){
				result.code=-1;
				result.msg="新增商票跟踪表数据异常";
			}
			

		}	

//		更新额度表状态
		cpl.comer_paper_status=status;
		cpl.reason=suggest;
		boolean  save=saveCommercialPaper(cpl);
		if(!save){
			result.code=-1;
			result.msg="额度表数异常，请稍后尝试";
			return result;
		}

		t_user tu = userservice.findByID(cpl.user_id);
		/** 发送邮件、站内信、短信通知用户 */
		Map<String, Object> content = new HashMap<String, Object>();
		content.put("user_name", tu.name);
		content.put("bill_code", cpl.bill_code);//质押票号
		content.put("suggest",suggest);	
		if(status==t_commercial_paper_lines.PaperStatus.REDEMPTION.code){
			/** 审核通过  发送通知 */
		}else if(status==t_commercial_paper_lines.PaperStatus.PLEDGE.code){
			/** 审核未通过  发送通知 */
		}
		result.code=1;
		return result;
	}
	/**
	 * 签字列表
	 *
	 * @param user_id
	 * @param type 0已签字  1 未签字查询
	 * @return
	 * @author xiaojun
	 *@version 2017-6-10
	 */
	public List<ShareholderSignBean> querySignatureList(String shareholder_name,int type,long user_id,String shareholder_mobile){
		return commerciaPaperLinesDao.querySignatureList(shareholder_name,type,user_id,shareholder_mobile);
		
	}
	/**
	 * 签字列表(APP)
	 *
	 * @param user_id
	 * @param type 0已签字  1 未签字查询
	 * @return
	 * @author xiaojun
	 *@version 2017-6-10
	 */
	public PageBean<ShareholderSignBean> querySignaturePageBean(String shareholder_name,int type,int currPage, int pageSize,long user_id,String shareholder_mobile){
		return commerciaPaperLinesDao.querySignaturePageBean(shareholder_name, type, currPage, pageSize,user_id,shareholder_mobile);
	}
	/**
	 * 签字列表--详情(APP)
	 *
	 * @param user_id
	 * @param type 0已签字  1 未签字查询
	 * @return
	 * @author xiaojun
	 *@version 2017-6-10
	 */
	public ShareholderSignBean querySignDetailed(String shareholder_name,long signId,long user_id,String shareholder_mobile){
		return commerciaPaperLinesDao.querySign(shareholder_name, signId,user_id,shareholder_mobile);
	}

	/**
	 * 托收准备
	 *
	 * @param cplid t_commercial_paper_lines实体id
	 * @return
	 * @author xiaojun
	 *@version 2017-6-16
	 */
	public ResultInfo readyCollection(long cplid){
		ResultInfo result = new ResultInfo();
		t_commercial_paper_lines cpl = findByID(cplid);
		if(cpl.comer_paper_status!=t_commercial_paper_lines.PaperStatus.EXPIRE.code){
			 result.code=-1;
			result.msg="状态非法";
			return result;
		}
//		修改状态
		cpl.comer_paper_status=PaperStatus.LOSE_EFFICACY.code;
		boolean save=saveCommercialPaper(cpl);
		if(!save){
			result.code=-1;
			result.msg="额度状态更新失败";
			return result;
		}
		t_digital_commercial_paper dcp=null;
		if(cpl.financing_type==1){
			dcp=digitalCommercialPaperService.findByID(cpl.financing_type_id);
			
		}else if(cpl.financing_type==2){
			t_endorse endorse =endorseService.findByID(cpl.financing_type_id);
			endorse.receive_endorse_status=DigitalStatus.LOSE_EFFICACY.code;
			save=digitalCommercialPaperService.saveDigitalPapreB(dcp);
			if(!save){
				result.code=-1;
				result.msg="背书流转状态更新失败";
				return result;
			}
			dcp=digitalCommercialPaperService.findByID(endorse.digital_id);
		}
		if(dcp!=null){
			dcp.digital_com_status=DigitalStatus.LOSE_EFFICACY.code;
			save=digitalCommercialPaperService.saveDigitalPapreB(dcp);
			if(!save){
				result.code=-1; 
				result.msg="数字商票状态更新失败";
				return result;
			}
		}	
		 result.code=1;
		 result.msg="托收成功！商票已兑现";
		return result;
	}
	/**
	 * 确认还款（准备）
	 *
	 * @param userId 用户ID
	 * @param 
	 * @return
	 *
	 * @author xiaojun
	 * @createDate 2015年12月28日
	 */
	public ResultInfo normalRepayment(long userId, t_commercial_paper_lines dcp) {
		ResultInfo result = new ResultInfo();
		
		if (dcp == null) {
			throw new InvalidParameterException("t_commercial_paper_lines is null");
		}
		
		t_user_fund userFund = userFundService.queryUserFundByUserId(userId);
		
		if (userFund == null) {
			result.code = -1;
			result.msg = "获取用户资金信息失败";
			
			return result;
		}
		
		/** 用户资金是否出现异常变动 */
		result = userFundService.userFundSignCheck(userId);
		if (result.code < 1) {
			
			return result;
		}
		
		/** 借款人资金是否充足 */
		double payAmt =  dcp.finacing_total_limit;
		if (userFund.balance < payAmt) {
			result.code = -4;
			result.msg = "余额不足";
			
			return result;
		}
		result.code = 1;
		result.msg = "还款准备完毕";
		return result;
	}
	
	/**
	 * 商票兑现状态更新
	 *
	 * @param id 数字商票id
	 * @return
	 * @author xiaojun
	 *@version 2017-5-23
	 */
	public ResultInfo stateChange(long  id,int olStatus){
		ResultInfo result = new ResultInfo();
		t_commercial_paper_lines cpl = findByID(id);
//      更新额度状态
		cpl.comer_paper_status = PaperStatus.LOSE_EFFICACY.code;
		boolean save= updateStatus(PaperStatus.LOSE_EFFICACY.code, olStatus, id);
		if(!save){
			result.code=-1;
			result.msg="商票额度状态更新失败";
		}
//      更新商票状态
		t_commercial_paper_info cpi=commerciaPaperiInfoService.findByID(cpl.commer_paper_id);
		cpi.cash_all_amount=cpi.paper_money;
		cpi.cash_amount=cpi.paper_money;
		cpi.cash_time=new Date();
		cpi.paper_status=t_commercial_paper_info.TicketStatus.ALL_SQUARED.code;
		cpi=commerciaPaperiInfoService.addTicket(cpi);
		if(cpi==null){
			result.code=-1;
			result.msg="商票状态更新失败";
		}

//		 修改额度表数据
		 t_commercial_paper_lines commercial_paper_lines=findByID(cpl.financing_type_id);
		 commercial_paper_lines.finacing_available_limit+=cpi.paper_money;
		 commercial_paper_lines.finacing_used_limit-=cpi.paper_money;
		save= saveCommercialPaper(commercial_paper_lines);
		if(!save){
			result.code=-1;
			result.msg="更新额度失败";
			return result;  
		}
		t_company_info company_info =companyInfoService.findCompanyInfoByUserId(commercial_paper_lines.user_id);
		t_creditor_right_debt crd=creditorRightDebtService.findByID(commercial_paper_lines.creditor_right_id);
//		添加额度明细表信息
		t_amount_detail amountDetail=new t_amount_detail(commercial_paper_lines.id,company_info.full_name,new Date(),cpi.paper_money,commercial_paper_lines.finacing_available_limit,CrawlType.CONFIRM_PAYMENT.code,crd.contract_name_code,cpl.finacing_total_limit);
		boolean saveDetail= amountDetailService.saveAmountDetail(amountDetail);
		if(!saveDetail){
			result.code=-1;
			result.msg="新增额度明细异常";
			return result;  
		}
		result.code=1;
		result.msg="执行成功！";
		return result;  
		
	}
	
	/**
	 * 确认还款（执行）
	 * 
	 * @param cplid 额度ID
	 * @param serviceOrderNo 业务订单号
	 * @return
	 *
	 * @author xiaojun
	 * @createDate 2017年5月23日
	 */
	public ResultInfo doRepayment(long cplid,  String serviceOrderNo,long user_id ) {
		ResultInfo result = new ResultInfo();
		
		t_commercial_paper_lines cpl = findByID(cplid);
		if (cpl == null) {
			result.code = -1;
			result.msg = "该商票额度信息不存在";
			
			return result;
		}

//		查询商票信息
		t_commercial_paper_info cpi=commerciaPaperiInfoService.findByID(cpl.commer_paper_id);
	    //质押人应收金额
		double receiveAmt = cpi.paper_money; 
	
		boolean isSignSuccess = true; 
		//用户签名是否通过
		result = userFundService.userFundSignCheck(cpl.user_id );
		if (result.code < 1) {
			isSignSuccess = false;
		}
		
		boolean addFund = userFundService.userFundAdd(cpl.user_id, receiveAmt);
		if (!addFund) {
			result.code = -1;
			result.msg = "增加持票人可用余额失败";
			return result;
		}
		//刷新持票人资金信息
		t_user_fund investUserFund = userFundService.queryUserFundByUserId(cpl.user_id);
		if (investUserFund == null) {
			result.code = -1;
			result.msg = "获取持票人资金信息失败";
			return result;
		}
		//添加质押人收款记录
		Map<String, String> summaryParam = new HashMap<String, String>();
		summaryParam.put("bill_code", cpi.bill_code);
		/*boolean addDeal = dealUserService.addDealUserInfo(
				serviceOrderNo,
				cpl.user_id, 
				cpi.paper_money, 
				investUserFund.balance,    //此时不计“投资服务费”和“逾期罚息”
				investUserFund.freeze, 
				t_deal_user.OperationType.DUE_PAYMENT,
				summaryParam);
		if (!addDeal) {
			result.code = -1;
			result.msg = "添加持票人收款记录失败";
			
			return result;
		}*/
//				冻结用户已用额度金额	
		if( cpl.finacing_used_limit>0){
			addFund = userFundService.userFundFreeze(cpl.user_id, cpl.finacing_used_limit);
			if (!addFund) {
				result.code = -1;
				result.msg = "冻结用户已用额度金额失败";
				return result;
			}
			//刷新持票人资金信息
			investUserFund = userFundService.queryUserFundByUserId(cpl.user_id);
			//用户资产签名更新
			userFundService.userFundSignUpdate(cpl.user_id);
			//添加质押人收款记录
			summaryParam = new HashMap<String, String>();
			summaryParam.put("bill_code", cpi.bill_code);
			/*addDeal = dealUserService.addDealUserInfo(
					serviceOrderNo,
					cpl.user_id, 
					cpl.finacing_used_limit, 
					investUserFund.balance,    //此时不计“投资服务费”和“逾期罚息”
					investUserFund.freeze, 
					t_deal_user.OperationType.FREEZE_AMOUNT,
					summaryParam);
			if (!addDeal) {
				result.code = -1;
				result.msg = "添加持票人收款记录失败";
				
				return result;
			}*/
		}
 			//通知质押人
 			Map<String, Object> sceneParame = new HashMap<String, Object>();
 			sceneParame.put("user_name", investUserFund.name);
 			sceneParame.put("bill_code",cpi.bill_code);
 			sceneParame.put("paper_money", receiveAmt);
 			noticeservice.sendSysNotice(cpl.user_id, NoticeScene.DUE_PAYMENT, sceneParame);
		
 			//出票人用户签名是否通过
 			result = userFundService.userFundSignCheck(user_id );
 			if (result.code < 1) {
 				isSignSuccess = false;
 			}
		/** 扣除出票人还款金额  */
		double repayAmt = cpi.paper_money;
		boolean minusFund = userFundService.userFundMinus(user_id, repayAmt);
		if (!minusFund) {
			result.code = -1;
			result.msg = "扣除开票人可用余额失败";
			
			return result;
		}
		
		//更新出票人资产签名更新
		userFundService.userFundSignUpdate(user_id);
		
		//刷新出票人资金信息
		t_user_fund loanUserFund = userFundService.queryUserFundByUserId(user_id);
		if (loanUserFund == null) {
			result.code = -1;
			result.msg = "获取开票人资金信息失败";
			
			return result;
		}
		
		//添加开票人还款记录
		 summaryParam = new HashMap<String, String>();
		summaryParam.put("bill_code", cpi.bill_code);
		/*addDeal = dealUserService.addDealUserInfo(
				serviceOrderNo,
				user_id, 
				cpi.paper_money, 
				loanUserFund.balance,   
				loanUserFund.freeze, 
				t_deal_user.OperationType.EXPIRE_REIMBURSEMENT,
				summaryParam);
		if (!addDeal) {
			result.code = -1;
			result.msg = "添加开票人还款记录失败";
			
			return result;
		}*/

		
		//通知借款人
		 sceneParame = new HashMap<String, Object>();
		sceneParame.put("user_name", loanUserFund.name);
			sceneParame.put("bill_code",cpi.bill_code);
			sceneParame.put("paper_money", receiveAmt);
		noticeservice.sendSysNotice(user_id, NoticeScene.EXPIRE_REIMBURSEMENT, sceneParame);
		
		result.code = 1;
		result.msg = "还款成功";
		
		
		return result;
	}
	
	/**
	 * 定时任务-商票质押额度逾期自动兑现（非原始商票）
	 *
	 * @return
	 * @author xiaojun
	 *@version 2017-5-24
	 */
	public ResultInfo systemTicketAmounOverdueCash(){
		ResultInfo result = new ResultInfo();
//		查出到期的质押商票
		List<t_commercial_paper_lines> list=commerciaPaperLinesDao.findAutoCash( t_commercial_paper_lines.PaperStatus.OVERDUE.code);
		if(list==null||list.size()==0){
			 result.code=1;
			 result.msg="没有商票质押逾期";
			return result;
		}
		/* 关闭自动事务 */
		   JPAPlugin.closeTx(false);
		for(t_commercial_paper_lines cpl:list){
			/* 开启自动投标事务 */
			JPAPlugin.startTx(false);
			result.msg="没有转开商票质押逾期";
			if(cpl.is_turned==1){
				result.msg="原商票未结清";
				t_commercial_paper_info oldcpi=commerciaPaperiInfoService.findByID(cpl.oiginal_id);
				if(oldcpi!=null&&oldcpi.paper_status==t_commercial_paper_info.TicketStatus.ALL_SQUARED.code){
					
					t_commercial_paper_info cpi=commerciaPaperiInfoService.findByID(cpl.commer_paper_id);
//					更新商票的状态为：已结清
					cpi.paper_status=TicketStatus.ALL_SQUARED.code;
					cpi.cash_all_amount=cpl.finacing_total_limit;
					cpi.cash_amount=cpl.finacing_total_limit;
					cpi.collection_status=1;
					cpi=commerciaPaperiInfoService.addTicket(cpi);
					if(cpi==null){
						result.code=-1;
						result.msg="商票状态更新失败";
					}
					t_company_info company_info=companyInfoService.findByColumn(" full_name=?", cpi.drawee);
					if(company_info==null){
						result.code=-1;
						result.msg="查询付款人信息失败";
					}
					 if(cpl.financing_type==1){
						t_digital_commercial_paper dcp= digitalCommercialPaperService.findByID(cpl.financing_type_id);
						
//				   		   更新数字商票状态
						dcp.digital_com_status=t_digital_commercial_paper.DigitalStatus.LOSE_EFFICACY.code;
						boolean save= digitalCommercialPaperService.saveDigitalPapreB(dcp);
						if(!save){
							result.code=-1;
							result.msg="数字商票状态更新失败";
						}
					}else if(cpl.financing_type==2){//背书后申请融通额度
						t_endorse endorse=endorseService.findByID(cpl.financing_type_id);
						t_digital_commercial_paper dcp= digitalCommercialPaperService.findByID(endorse.digital_id);
						
//				   		   更新数字商票状态
						dcp.digital_com_status=DigitalStatus.LOSE_EFFICACY.code;
						boolean save= digitalCommercialPaperService.saveDigitalPapreB(dcp);
						if(!save){
							result.code=-1;
							result.msg="数字商票状态更新失败";
						}
//				   		   更新背书流转状态
						 endorse.receive_endorse_status=DigitalStatus.LOSE_EFFICACY.code;	
							save= endorseService.saveEndorse(endorse);
							if(!save){
								result.code=-1;
								result.msg="背书状态更新失败";
							}
					}
//					订单号
					String serviceOrderNo = OrderNoUtil.getNormalOrderNo(ServiceType.TICKET_CASH,OrderNoUtil.COMMERICAL_ORDER_NORMAL);
						result=doAutoCash(cpl.id, serviceOrderNo);
						if (result.code < 0) {
							 result.code=-1;
							 result.msg="自动兑换商票金额失败";
							return result;
						}
				}
			}
			/* 关闭自动事务 */
			   JPAPlugin.closeTx(false);
		}
		/* 开启自动投标事务 */
		JPAPlugin.startTx(false);
		result.code=1;
		return result;
	}
	
	/**
	 * 定时任务 标的融通到期还款
	 * @return
	 * @author xiaojun
	 * @version 2017-5-3 
	 */
 	public ResultInfo bidExpireCash(){
		ResultInfo result = new ResultInfo();
		int type=0;
		//查询今天到期挂牌标的
		/*List<Map<String, Object>> listOfWillExpireTicket = bidService.querylistOfWillBidExpire(type);
	
		if (listOfWillExpireTicket==null || listOfWillExpireTicket.size()==0) {
			result.code = 1;
			result.msg = "当前没有需要还款的到期标的!";
			
			return result;
		}
		for(Map<String, Object> mapBill : listOfWillExpireTicket){
			if(mapBill.get("userId")!=null){
				long consult_id=Long.parseLong(mapBill.get("consult_id").toString());
				t_commercial_paper_lines cpl = findByID(consult_id);
				t_commercial_paper_info cpi = commerciaPaperiInfoService.findByID(cpl.commer_paper_id);
				result.msg = "商票未兑现，无法执行标的自动还款";
				if(cpi.cash_all_amount == cpl.finacing_total_limit && cpi.paper_status == TicketStatus.ALL_SQUARED.code){
					String serviceOrderNo = OrderNoUtil.getNormalOrderNo(ServiceType.USER_UNFREEZE,OrderNoUtil.COMMERICAL_ORDER_NORMAL);
//					 还款
					long bid_id = Convert.strToLong(mapBill.get("id").toString(),0);
					List<t_bill> bills = billService.findBillByBidId(bid_id);
					if (bills.isEmpty()) {
						LoggerUtil.error(true, result.msg);
						return result;
					}
					t_bill bill = bills.get(0);
					
					if(bill.getStatus().code != t_bill.Status.NORMAL_NO_REPAYMENT.code){
						result.code = -1;
						LoggerUtil.error(true, result.msg);
						return result;
					}
					//执行还款
					result = billService.normalRepayment(cpl.user_id, bill);
					if (result.code < 1) {
							LoggerUtil.info(true, result.msg);
							return result;
					}
					List<Map<String, Double>> billInvestFeeList = (List<Map<String, Double>>) result.obj;
					//4、查询在还款的时候有没有竞价没有完成，没完成的进行资金解冻
					List<DebtBack> debtBacks = debtService.queryBackBidFund( bill.bid_id);
					//定义是否需要进行资金的解冻
					boolean flag = false;
					if (null != debtBacks && debtBacks.size() != 0) {
						flag = true;
					}
					result = billService.doRepayment(bill.id, billInvestFeeList, serviceOrderNo,bill.user_id);
					if (result.code < 1 && result.code != ResultInfo.ALREADY_RUN) {
								LoggerUtil.info(true, result.msg);
								return result;
					} 
					//t_debt_tansfer的订单号
					String serviceOrderNoDebt = OrderNoUtil.getNormalOrderNo(ServiceType.DEBT_TRANSFER,"");
					//进行用户的资金解冻，竞价没有完成,此时解冻之前的的竞价转，我们只考虑竞价转让成功之后的操作，没有成公的时候我们不会去变更数据
					// 未还款 逾期的情况 也是可以进行转让 的
					if (flag) {
						 //批量进行资金的解冻，解冻资金为当时的竞价资金
					     //暂时如此执行，资金解冻的批量操作暂时
						 for (DebtBack baackBack : debtBacks) {
							result = debtService.doDebtBiddUnFrozen(serviceOrderNoDebt,  baackBack.id, baackBack.user_id, baackBack.amount.doubleValue());  
							if (result.code < 1) {
								LoggerUtil.info(true, result.msg);
								return result;								
							}
							result = debtService.updateDebtTransfer(  baackBack.id, t_debt_transfer.Status.INVALID);
							if (result.code < 1) {
								LoggerUtil.info(true, result.msg);
								return result;
							}
					     }
					}			
					return result;
								
					
				}
			}else {
				result.code = -1;
				result.msg = "数据出错，没有用户id";
				return result;
			}
		}*/
		return result;
 	}
 	/**
 	 * 查询 用户是否有额度
 	 *
 	 * @param user_id 用户id
 	 * @return
 	 * @author xiaojun
 	 *@version 2017-7-4
 	 */
	public  List<t_commercial_paper_lines> queryListbyStatus(long user_id){
		List<Integer>nowstatus = new ArrayList<Integer>();
		nowstatus.add(PaperStatus.PREAUDITING.code);
		nowstatus.add(PaperStatus.PLEDGE.code);
		nowstatus.add(PaperStatus.EXPIRE.code);
		nowstatus.add(PaperStatus.OVERDUE.code);
		nowstatus.add(PaperStatus.TO_SIGNATURE.code);
		nowstatus.add(PaperStatus.SIGNATURE.code);
		nowstatus.add(PaperStatus.TO_RELEVANCE.code);
		nowstatus.add(PaperStatus.RELEVANCE.code);
		nowstatus.add(PaperStatus.SIGN_FOR.code);
		nowstatus.add(PaperStatus.REDEMPTION_REQUESTS.code);
		return commerciaPaperLinesDao.queryListbyStatus(user_id,nowstatus);
	}
	
	/**
	 * 发起签字通知
	 *
	 * @param id
	 * @param user_name
	 * @param getIp
	 * @return
	 * @author xiaojun
	 *@version 2017-8-1
	 */
	public ResultInfo signedAgreement(long id,String getIp){
		ResultInfo result = new ResultInfo();
		t_commercial_paper_lines cpl = findByID(id);
		if(cpl == null){
			result.code = -1;
			result.msg = "没有找到额度信息！";
			return result;
		}
		t_user user = userservice.findByID(cpl.user_id);
		
		//用户发起签字通知
		Map<String, Object> content = new HashMap<String, Object>();
		content.put("user_name", user.company_full_name);
		content.put("bill_code", cpl.bill_code);//质押票号
		List<t_shareholder> shareholderList=shareholderService.findBindByCompanyId(cpl.user_id);//currUser.id
		if(shareholderList == null || shareholderList.size() == 0){
			result.code = -1;
			result.msg = "股东没有绑定成功！";
			return result;
		}
		int sum=0;
		for (t_shareholder t : shareholderList) {
				
				if(t.getHoldControllingType().code ==  HoldControllingType.IS_SHAREHOLDER_COMPANY.code || t.getHoldControllingType().code ==  HoldControllingType.REAL_CONTROLLER_COMPANY.code){
					content.put("sh_name", t.company_full_name);
					t.sh_mobile=t.legal_person_mobile;
				}else {
					content.put("sh_name", t.sh_name);
				}
		    	/* 根据手机号码查询短信发送条数 */
				List<t_send_code> recordByMobile = sendCodeRecordsService.querySendRecordsByMobile(t.sh_mobile);
		    	if(recordByMobile.size() >= ConfConst.SEND_SMS_MAX_MOBILE){
					result.code = -1;
					result.msg = "该手机号码单日短信发送已达上限！";
					return result;
		    	}
				if(t.user_id!=0){
					noticeservice.sendSysNotice(t.user_id, NoticeScene.SHAREHOLDERS_TO_SIGN, content);
				}else {
					Map<String, String> template_content = new HashMap<String, String>();
					content.put("sh_name",  user.company_full_name);
					content.put("bill_code", cpl.bill_code);//质押票号
					result = noticeservice.toSendEmail(t.sh_mobile,t.sh_email,NoticeScene.SHAREHOLDERS_TO_SIGN,template_content);	
					if(result.code < 1){
						continue;
					}
					
				}
				/* 添加一条短信发送控制记录 */
				sendCodeRecordsService.addSendCodeRecords(t.sh_mobile, getIp);
				sum++;
				if(sum==3){
					break;
				}
		}
		result.code = 1;
		result.msg = "发起签字通知成功！";
		return result;
	}
	
	
	 /**
	  * 校验
	  *
	  * @param creditorId 债务id
	  * @param paper_money 金额
	  * @param cpl 额度实体
	  * @param crd 债权实体
	  * @param digitalCommercialPaper 数字商票实体
	  * @param payment_time 到期时间
	  * @return
	  * @author xiaojun
	  *@version 2017-11-17
	  */
	 public ResultInfo savePaperValidate(long creditorId,double paper_money,t_commercial_paper_lines cpl,t_creditor_right_debt crd,t_digital_commercial_paper digitalCommercialPaper,String payment_time){
		 ResultInfo result=new ResultInfo();
		 if(creditorId<=0){
				result.code =-1;
				result.msg = "请选择债务信息";
				return result;
		 }
		if(paper_money<=0){
			result.code =-1;
			result.msg = "转开金额异常";
			return result;
		}
		if(paper_money>cpl.finacing_available_limit){
			result.code =-1;
			result.msg = "转开金额不能大于融通可用额度";
			return result;
		}
		if(paper_money>crd.rest_debt_money){
			result.code =-1;
			result.msg = "转开金额不能大于融通可用额度";
			return result;
		}
		if(payment_time==null){
			result.code =-1;
			result.msg = "到期时间不能为空";
			return result;
		}
		if (!StrUtil.is_date(payment_time)) {
			result.code =-1;
			result.msg = "到期时间格式不对";
			return result;
		}
		try {
			digitalCommercialPaper.payment_time=DateToIntUtil.stringToDate(payment_time);
		} catch (Exception e) {
			result.code =-1;
			result.msg = "时间格式不对";
			return result;
		}
		Date paper_expire_time=DateUtil.addDay(cpl.paper_expire_time, 10);
		if(DateToIntUtil.dateToDay(digitalCommercialPaper.payment_time)  < DateToIntUtil.dateToDay(paper_expire_time)){
			result.code =-1;
			result.msg = "商票到期时间必须在" + DateUtil.dateToString(paper_expire_time, "yyyy/MM/dd") + "之后";
			return result;
		}
		if(DateToIntUtil.dateToDay(digitalCommercialPaper.payment_time)  > DateToIntUtil.dateToDay(DateUtil.addDay(cpl.paper_expire_time, 360))){
			result.code =-1;
			result.msg = "商票到期时间必须在" + DateUtil.dateToString(DateUtil.addDay(cpl.paper_expire_time, 360), "yyyy/MM/dd") + "之内";
			return result;
		}
		result.code = 1;
		result.msg = "校验通过";
		return result;
	 }
	 
	 /**
	  * 查询已使用额度上限
	  *
	  * @return
	  * @author xiaojun
	  *@version 2017-10-28
	  */
	 /* public double queryMaxLimit(long user_id){
		  List<Integer> comer_paper_status =new ArrayList<Integer>();
		  comer_paper_status.add(t_commercial_paper_lines.PaperStatus.PLEDGE.code);
		  comer_paper_status.add(t_commercial_paper_lines.PaperStatus.EXPIRE.code);
		  comer_paper_status.add(t_commercial_paper_lines.PaperStatus.OVERDUE.code);
		  comer_paper_status.add(t_commercial_paper_lines.PaperStatus.RELEVANCE.code);
		  comer_paper_status.add(t_commercial_paper_lines.PaperStatus.REDEMPTION_REQUESTS.code);
		  comer_paper_status.add(t_commercial_paper_lines.PaperStatus.REDEMPTION.code);
		  comer_paper_status.add(t_commercial_paper_lines.PaperStatus.TO_HANGTAG.code);
		  return commerciaPaperLinesDao.queryMaxLimit(user_id, comer_paper_status);
	  }*/

	
	/**
	 * 根据bid查询票号
	 *
	 * @param investId
	 * @return
	 * @author xiaojun
	 *@version 2017-12-4
	 */
	public String queryBillcode(long bid_id){
		String sql = "SELECT cpi.bill_code FROM  t_bid bid  LEFT JOIN t_commercial_paper_lines cpl ON cpl.id = bid.consult_id LEFT JOIN t_commercial_paper_info cpi ON cpi.id = cpl.commer_paper_id WHERE bid.id = :bid_id";
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("bid_id", bid_id);
		return commerciaPaperLinesDao.findSingleStringBySQL(sql, "0", condition);
	}
}
